package com.by.service.impl;

import cn.hutool.core.map.MapUtil;
import com.by.bean.Product;
import com.by.common.bean.PageBean;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.utils.Assert;
import com.by.mapper.ProductBannerMapper;
import com.by.mapper.ProductMapper;
import com.by.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product, ProductMapper> implements ProductService {

    @Autowired
    ProductBannerMapper productBannerMapper;

    @Autowired
    HttpServletRequest request;

    @Transactional
    @Override
    public int save(Product entity) {
        //保存产品
        int rs = super.save(entity);
        Assert.isNotSuccess(rs, "保存产品失败");
        //成功了 保存轮播图
        if (null != entity.getBanner() && entity.getBanner().size() > 0) {
            rs = productBannerMapper.save(entity.getId(), entity.getBanner());
            Assert.isNotSuccess(rs, "保存产品轮播图失身");
        }
        return 1;
    }

    @Transactional
    @Override
    public int update(Product entity) {
        //修改产品
        int rs = super.update(entity);
        Assert.isNotSuccess(rs, "产品修改失败");
        //1. 删除的图片 从服务器目录下删除
        //2.
        //删除之前的
        productBannerMapper.deleteByProduct(entity.getId());
        //插入
        //成功了 保存轮播图
        if (null != entity.getBanner() && entity.getBanner().size() > 0) {
            rs = productBannerMapper.save(entity.getId(), entity.getBanner());
            Assert.isNotSuccess(rs, "保存产品轮播图失身");
        }

        return 1;
    }


    /**
     * 删除图片
     * @param path 图片的相对路径
     */
    void rmpic(String path) {
        //获取服务器根路径
        String root = request.getServletContext().getRealPath("/");
        File file = new File(root + path);
        //删除
        file.delete();
    }

    @Override
    public List queryAll() {
        return baseMapper.queryAll();
    }

    @Override
    public PageBean queryCust(Map map) {
        int page = MapUtil.getInt(map, "page");
        int pageSize = MapUtil.getInt(map, "pageSize");
        //设置分页
        PageHelper.startPage(page, pageSize);// 后面紧跟查询
        List<Map> list = baseMapper.queryCust(map);

        //获取分页信息 将查询结果封装一下
        PageInfo info = new PageInfo(list);

        return new PageBean(page, pageSize, info.getTotal(), list);
    }
}
